package com.zb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.entity.*;
import com.zb.extend.KnowledgeTypeFaultExtend;
import com.zb.mapper.ZjFaultMapper;
import com.zb.mobile.MobileFaultDetailVo;
import com.zb.result.PageUtil;
import com.zb.service.ZjFaultAnnexService;
import com.zb.service.ZjFaultService;
import com.zb.service.ZjFaultSolutionService;
import com.zb.service.ZjKnowledgeTypeFaultService;
import com.zb.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WEN
 * @since 2023-07-31
 */
@Service
public class ZjFaultServiceImpl extends ServiceImpl<ZjFaultMapper, ZjFault> implements ZjFaultService {
    @Resource
    private ZjFaultMapper faultMapper;
    @Resource
    private ZjFaultAnnexService faultAnnexService;
    @Resource
    private ZjFaultSolutionService faultSolutionService;
    @Resource
    private ZjKnowledgeTypeFaultService knowledgeTypeFaultService;

    // 新增或修改故障
    @Override
    @Transactional
    public void save(Long custAccId, FaultVo faultVo) {
        Assert.isTrue(null == faultMapper.existByName(custAccId, faultVo.getId(), faultVo.getName()), "故障名称重复", faultVo.getName());

        ZjFault fault = new ZjFault();
        BeanUtils.copyProperties(faultVo, fault);
        fault.setDisabled(faultVo.getStatus());

        if (null != fault.getId()) {
            fault.setId(faultVo.getId());
            this.updateById(fault);
        } else {
            fault.setId(IdWorker.getId());
            fault.setCustAccId(custAccId);
            this.save(fault);
        }
        faultAnnexService.save(custAccId, fault.getId(), faultVo.getAnnexs(), faultVo.getDelAnnexIds());
        faultSolutionService.save(custAccId, fault.getId(), faultVo.getSolutions(), faultVo.getDelSolutionIds());
        knowledgeTypeFaultService.save(custAccId, fault.getId(), faultVo.getKnowledgeTypeVos(), faultVo.getDelRelationIds());
    }

    // 获取故障列表
    @Override
    public Map<String, Object> getList(Long custAccId, FaultSelectVo faultSelectVo) {
        QueryWrapper<ZjFault> wrapper = new QueryWrapper<>();
        wrapper.eq("cust_acc_id", custAccId);
        wrapper.orderByDesc("gmt_update");
        if (StringUtils.isNotBlank(faultSelectVo.getName())) {
            wrapper.like("name", faultSelectVo.getName());
        }
        if (StringUtils.isNotBlank(faultSelectVo.getContent())) {
            wrapper.like("content", faultSelectVo.getContent());
        }
        if (StringUtils.isNotBlank(faultSelectVo.getSolution())) {
            wrapper.like("solution", faultSelectVo.getSolution());
        }
        PageUtil.setPageLimit(faultSelectVo);
        Page<ZjFault> page = this.page(new Page<>(faultSelectVo.getPage(), faultSelectVo.getLimit()), wrapper);

        List<KnowledgeTypeFaultExtend> faultExtendList = knowledgeTypeFaultService.getbyFaultIds(page.getRecords().stream().map(ZjFault::getId).toList());
        List<FaultsVo> voList = page.getRecords().stream().map(t -> {
            FaultsVo vo = FaultsVo.beanToVo(t);
            vo.setKnowledgeType(faultExtendList.stream().filter(f -> Objects.equals(f.getFaultId(), t.getId())).map(KnowledgeTypeFaultExtend::getName).collect(Collectors.joining("、")));
            return vo;
        }).toList();
        return PageUtil.pageList(page.getCurrent(), page.getSize(), page.getTotal(), voList);
    }

    // 根据ID获取故障详情
    @Override
    public FaultVo getInfo(Long id) {
        ZjFault fault = this.getById(id);
        Assert.isTrue(null != fault, "故障参数[" + id + "]的数据不存在");
        FaultVo vo = new FaultVo();
        BeanUtils.copyProperties(fault, vo);
        vo.setStatus(fault.getDisabled());
        vo.setAnnexs(faultAnnexService.getByFaultId(id).stream().map(annex -> {
            return new FaultAnnexVo(annex.getId(), annex.getPath());
        }).toList());
        vo.setSolutions(faultSolutionService.getByFaultId(id).stream().map(so -> {
            return new FaultAnnexVo(so.getId(), so.getPath());
        }).toList());
        vo.setKnowledgeTypeVos(knowledgeTypeFaultService.getByFaultId(id).stream().map(type -> {
            return new KnowledgeTypeRelationVo(type.getId(), type.getKnowledgeTypeId());
        }).toList());
        return vo;
    }

    // 批量启用或禁用故障
    @Override
    public void updateBatchDisableByIds(List<Long> idList, boolean disable) {
        faultMapper.updateBatchDisableByIds(idList, disable);
    }

    // 根据ID集合查询故障名称
    @Override
    public List<String> getNameByIds(List<Long> idList) {
        if (null == idList || idList.isEmpty()) {
            return new ArrayList<>();
        }
        return faultMapper.getNameByIds(idList);
    }

    // 批量删除故障
    @Override
    @Transactional
    public void deleteBatchById(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return;
        }
        knowledgeTypeFaultService.deleteBatchByFaultId(ids);
        faultSolutionService.deleteBatchByFaultId(ids);
        faultAnnexService.deleteBatchByFaultId(ids);
        this.removeByIds(ids);
    }

    // 根据故障库ID获取故障详情内容
    @Override
    public MobileFaultDetailVo getUserMobileFaultDetail(Long id) {
        ZjFault fault = this.getById(id);
        Assert.isTrue(null != fault, "故障库的数据不存在");

        MobileFaultDetailVo vo = new MobileFaultDetailVo();
        BeanUtil.copyProperties(fault, vo);
        vo.setPath(faultAnnexService.getByFaultId(id).stream().map(ZjFaultAnnex::getPath).toList());
        vo.setSolutionPath(faultSolutionService.getByFaultId(id).stream().map(ZjFaultSolution::getPath).toList());
        return vo;
    }

    // 根据[知识库分类ID]获取故障库
    @Override
    public Object getFailt(Long knowledgeTypeId) {
        QueryWrapper<ZjKnowledgeTypeFault> typeFaultQueryWrapper = new QueryWrapper<>();
        typeFaultQueryWrapper.select("knowledge_type_id", "fault_id");
        typeFaultQueryWrapper.in("knowledge_type_id", knowledgeTypeId);
        List<ZjKnowledgeTypeFault> typeFaultList = knowledgeTypeFaultService.list(typeFaultQueryWrapper);
        if (CollectionUtil.isEmpty(typeFaultList)) {
            return new ArrayList<>();
        }
        QueryWrapper<ZjFault> faultQueryWrapper = new QueryWrapper<>();
        faultQueryWrapper.select("id", "name", "content", "solution");
        faultQueryWrapper.in("id", typeFaultList.stream().map(ZjKnowledgeTypeFault::getFaultId).toList());
        List<ZjFault> faultList = this.list(faultQueryWrapper);
        return faultList.stream().map(fault -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", fault.getId());
            map.put("name", fault.getName());
            map.put("content", fault.getContent());
            map.put("solution", fault.getSolution());
            return map;
        }).toList();
    }


}
